<template>
  <div class="babyRadio-container" :style="`min-height: ${height || 40}px`">
    <div v-for="(radio, index) in radios" :key="index" class="line">
      <div class="row">
        <div
          v-for="(item, i) in radio"
          :key="item.value"
          class="item"
          :class="{
            active: item.active,
            fixWidth: !!fixWidth,
            anotherStyle: anotherStyle
          }"
          :style="
            `margin-bottom:${marginBottom}px;width:${
              fixWidth ? fixWidth + 'px' : 'auto'
            }`
          "
          @click="toogle(index, i)"
        >
          {{ item.label }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import _ from 'lodash';

export default {
  props: {
    items: [Array],
    height: [Number],
    resVal: {},
    marginRight: {
      type: Number,
      require: false,
      default: 10
    },
    marginBottom: {
      type: Number,
      require: false,
      default: 0
    },
    fixWidth: {
      type: Number,
      require: false,
      default: 0
    },
    anotherStyle: {
      type: Boolean,
      require: false,
      default: false
    }
  },
  computed: {
    radios() {
      return _.chunk(this.items, 4);
    }
  },
  watch: {
    resVal: {
      handler(v) {
        let i = 0;
        this.items.forEach((it, index) => {
          if (v === it.value) {
            i = index;
          }
        });
        this.toogle(i);
      },
      immediate: true
    }
  },
  methods: {
    toogle(i, j) {
      const index = i * 4 + j;
      if (this.items.length === 0) return;
      const newItems = JSON.parse(JSON.stringify(this.items));
      newItems.forEach(it => {
        it.active = false;
      });
      newItems[index].active = true;
      this.$emit('update:items', newItems);
      this.$emit('update:resVal', newItems[index].value);
    }
  }
};
</script>
<style lang="scss" scoped>
.babyRadio-container {
  display: flex;
  flex-direction: column;
  .line {
    background-color: #f2f6ff;
    margin-bottom: 8px;
    padding-top: 8px;
    padding-bottom: 8px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .row {
    margin-left: auto;
    margin-right: auto;
    display: flex;
    align-items: center;
    width: 1040px;
  }
  .item {
    height: 28px;
    box-sizing: border-box;
    border-radius: 15px;
    padding: 0 20px;
    border: 1px solid #b3b3b3;
    background-color: #fff;
    line-height: 28px;
    color: #666;
    margin-left: 80px;
    font-size: 16px;
    cursor: pointer;
    text-align: center;
    &:first-child {
      margin-left: 0;
    }
    &.active {
      background-color: #ffb03e;
      border: 1px solid #ffb03e;
      color: #fff;
    }
  }
  .anotherStyle {
    border: 1px solid #827d7d;
    color: #827d7d;
  }
  .fixWidth {
    padding: 0;
  }
}
</style>
